package com.company.netty;

import java.nio.charset.StandardCharsets;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

public class MessageEncoder extends MessageToByteEncoder<CustomMessage> {
    @Override
    protected void encode(ChannelHandlerContext ctx, CustomMessage msg, ByteBuf out) {
        byte[] contentBytes = msg.getContent().getBytes(StandardCharsets.UTF_8);
        // 协议格式: [类型(4字节)][长度(4字节)][内容]
        out.writeInt(msg.getType());
        out.writeInt(contentBytes.length);
        out.writeBytes(contentBytes);
    }
}
